const baseURL = 'http://127.0.0.1:8008'

// 创建请求对象
const request = {
  baseURL, // 导出baseURL供其他模块使用

  // 请求拦截器
  async beforeRequest(options = {}) {
    // 添加基础URL
    options.url = baseURL + options.url

    // 获取token
    const token = uni.getStorageSync('token')

    // 合并header
    options.header = {
      'Content-Type': 'application/json',
      ...options.header
    }

    // 如果有token且header中没有Authorization，则添加
    if (token && !options.header['Authorization']) {
      options.header['Authorization'] = `Bearer ${token}`
    }

    return options
  },

  // 响应拦截器
  async handleResponse(response) {
    // 处理响应
    if (!response.statusCode) {
      throw new Error('网络请求失败，请检查网络连接')
    }

    if (response.statusCode !== 200) {
      throw new Error(`请求失败，状态码：${response.statusCode}`)
    }

    const { data } = response

    // 如果响应直接是数据对象（登录接口可能直接返回token）
    if (typeof data === 'object' && !data.hasOwnProperty('code')) {
      return data
    }

    // 处理标准响应格式
    if (data.code !== 200) {
      // token过期或无效
      if (data.code === 401) {
        // 清除token和用户信息
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')

        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/index'
        })
        throw new Error(data.message || '未授权，请重新登录')
      }
      throw new Error(data.message || '请求失败')
    }

    // 返回实际的业务数据
    return data.data
  },

  // GET请求
  get(url, params = {}, options = {}) {
    return new Promise(async (resolve, reject) => {
      try {
        const requestOptions = await this.beforeRequest({
          url,
          method: 'GET',
          data: params,
          ...options
        })

        uni.request({
          ...requestOptions,
          success: async (res) => {
            try {
              const data = await this.handleResponse(res)
              resolve(data)
            } catch (error) {
              reject(error)
            }
          },
          fail: (error) => {
            reject(new Error(error.errMsg || '网络请求失败'))
          }
        })
      } catch (error) {
        reject(error)
      }
    })
  },

  // POST请求
  post(url, data = {}, options = {}) {
    return new Promise(async (resolve, reject) => {
      try {
        const requestOptions = await this.beforeRequest({
          url,
          method: 'POST',
          data,
          ...options
        })

        uni.request({
          ...requestOptions,
          success: async (res) => {
            try {
              const data = await this.handleResponse(res)
              resolve(data)
            } catch (error) {
              reject(error)
            }
          },
          fail: (error) => {
            reject(new Error(error.errMsg || '网络请求失败'))
          }
        })
      } catch (error) {
        reject(error)
      }
    })
  },

  // DELETE请求
  delete(url, data = {}, options = {}) {
    return new Promise(async (resolve, reject) => {
      try {
        const requestOptions = await this.beforeRequest({
          url,
          method: 'DELETE',
          data,
          ...options
        })

        uni.request({
          ...requestOptions,
          success: async (res) => {
            try {
              const data = await this.handleResponse(res)
              resolve(data)
            } catch (error) {
              reject(error)
            }
          },
          fail: (error) => {
            reject(new Error(error.errMsg || '网络请求失败'))
          }
        })
      } catch (error) {
        reject(error)
      }
    })
  }
}

export default request 